package com.taiji.dianthus.service.http.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taiji.dianthus.common.BusinessMessage;
import com.taiji.dianthus.service.http.HttpAPIService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName HttpAPIServiceImpl
 * @Description
 * @Author H.M
 * @Date 2020/5/7
 */
@Service
public class HttpAPIServiceImpl implements HttpAPIService {

    Log log = LogFactory.getLog(HttpAPIServiceImpl.class);

    @Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private RequestConfig config;

    /**
     * 不带参get请求
     *
     * @param url
     * @return
     */
    @Override
    public BusinessMessage doGet(String url) {
        BusinessMessage message = new BusinessMessage();
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);
        // 装载配置信息
        httpGet.setConfig(config);
        CloseableHttpResponse response = null;
        // 发起请求
        try {
            response = this.httpClient.execute(httpGet);
            Integer code = response.getStatusLine().getStatusCode();
            message.setCode(code.toString());
            if (200 == code) {
                message.setSuccess(true);
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                JSONObject jsonObject = JSONObject.parseObject(result);
                message.setCode(jsonObject.get("code").toString());
                message.setMsg(jsonObject.get("msg").toString());
                message.setData(jsonObject.get("data"));
                message.setSuccess((boolean) jsonObject.get("success"));
            }
        } catch (IOException e) {
            message.setMsg("请求异常");
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
                message.setMsg("请求异常");
                return message;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return message;
    }

    /**
     * 查询链接可访问
     *
     * @param url
     * @return
     */
    @Override
    public BusinessMessage isAddressable(String url) {
        BusinessMessage message = new BusinessMessage();
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);
        // 装载配置信息
        httpGet.setConfig(config);
        CloseableHttpResponse response = null;
        // 发起请求
        try {
            response = this.httpClient.execute(httpGet);
            Integer code = response.getStatusLine().getStatusCode();
            message.setCode(code.toString());
            if (200 == code) {
                message.setSuccess(true);
                message.setMsg("请求成功");
            }
        } catch (IOException e) {
            message.setMsg("请求异常");
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
                message.setMsg("请求异常");
                return message;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return message;
    }


    /**
     * 带参get请求
     *
     * @param url
     * @param
     * @return
     */
    @Override
    public BusinessMessage doGet(String url, Map<String, Object> map) {
        BusinessMessage message = new BusinessMessage();
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            if (null != map) {
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    uriBuilder.addParameter(entry.getKey(), entry.getValue().toString());
                }
            }
            message = this.doGet(uriBuilder.build().toString());
        } catch (Exception e) {
            e.printStackTrace();
            message.setMsg("方法执行出错");
            message.setData(e.getMessage());
        }
        return message;
    }


    /**
     * 带参post请求
     *
     * @param url
     * @param map
     * @return
     */
    @Override
    public BusinessMessage doPost(String url, Map<String, Object> map) {
        BusinessMessage message = new BusinessMessage();
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);
        CloseableHttpResponse response = null;
        try {
            // 判断map是否为空，不为空则进行遍历，封装from表单对象
            if (map != null) {
                List<NameValuePair> list = new ArrayList<>();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
                // 构造from表单对象
                UrlEncodedFormEntity urlEncodedFormEntity = null;
                urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
                // 把表单放到post里
                httpPost.setEntity(urlEncodedFormEntity);
            }

            // 发起请求
            response = this.httpClient.execute(httpPost);
            Integer code = response.getStatusLine().getStatusCode();
            if (200 == code) {
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                JSONObject jsonObject = JSONObject.parseObject(result);
                message.setData(jsonObject.get("data"));
                message.setCode(jsonObject.get("code").toString());
                message.setMsg(jsonObject.get("msg").toString());
                message.setSuccess((boolean) jsonObject.get("success"));
            }
        } catch (UnsupportedEncodingException e) {
            message.setMsg("数据格式化失败");
            log.error("数据格式化失败");
        } catch (ClientProtocolException e) {

            message.setMsg("接口数据序列异常");
            log.error("接口数据序列异常");
        } catch (IOException e) {
            message.setMsg("远程接口调用异常");
            log.error("远程接口调用异常");
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return message;
            }
        }
        return message;
    }

    @Override
    public BusinessMessage doPost(String url, JSONArray jsonArray) {
        BusinessMessage message = new BusinessMessage();
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);
        CloseableHttpResponse response = null;
        try {
            // 判断jsonArray是否为空，不为空则进行遍历，封装from表单对象
            if (null != jsonArray) {
                StringEntity stringEntity = new StringEntity(jsonArray.toString(), "UTF-8");
                log.info(jsonArray.toString());
                httpPost.setEntity(stringEntity);
            } else {
                httpPost.setEntity(null);
            }
            // 发起请求
            response = this.httpClient.execute(httpPost);
            Integer code = response.getStatusLine().getStatusCode();
            if (200 == code) {
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                JSONObject jsonObject = JSONObject.parseObject(result);
                message.setCode(jsonObject.get("code").toString());
                message.setMsg(jsonObject.get("msg").toString());
                message.setData(jsonObject.get("data"));
                message.setSuccess((boolean) jsonObject.get("success"));
            }
        } catch (UnsupportedEncodingException e) {
            message.setMsg("数据格式化失败");
            log.error("===========数据格式化失败，数据为" + jsonArray.toJSONString());
        } catch (ClientProtocolException e) {
            message.setMsg("服务端初始化失败");
            log.error("============服务端初始化失败，URL地址：" + url);
        } catch (IOException e) {
            message.setMsg("服务URL连接异常");
            log.error("============服务URL连接异常，URL地址：" + url);
        } catch (Exception e) {
            message.setMsg("系统异常");
            log.error("================其他错误==============");
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return message;
            }
        }
        return message;
    }

    @Override
    public BusinessMessage doPost(String url, String param) {
        BusinessMessage message = new BusinessMessage();
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);
        CloseableHttpResponse response = null;
        try {
            // 判断jsonArray是否为空，不为空则进行遍历，封装from表单对象
            if (null != param) {
                StringEntity stringEntity = new StringEntity(param, "UTF-8");
                log.info(param);
                httpPost.setEntity(stringEntity);
            } else {
                httpPost.setEntity(null);
            }
            // 发起请求
            response = this.httpClient.execute(httpPost);
            Integer code = response.getStatusLine().getStatusCode();
            if (200 == code) {
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                JSONObject jsonObject = JSONObject.parseObject(result);
                message.setCode(jsonObject.get("code").toString());
                message.setMsg(jsonObject.get("msg").toString());
                message.setData(jsonObject.get("data"));
                message.setSuccess((boolean) jsonObject.get("success"));
            }
        } catch (UnsupportedEncodingException e) {
            message.setMsg("数据格式化失败");
            log.error("===========数据格式化失败，数据为" + param);
        } catch (ClientProtocolException e) {
            message.setMsg("服务端初始化失败");
            log.error("============服务端初始化失败，URL地址：" + url);
        } catch (IOException e) {
            message.setMsg("服务URL连接异常");
            log.error("============服务URL连接异常，URL地址：" + url);
        } catch (Exception e) {
            message.setMsg("系统异常");
            log.error("================其他错误==============");
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return message;
            }
        }
        return message;
    }

    /**
     * 不带参post请求
     *
     * @param url
     * @return
     */
    @Override
    public BusinessMessage doPost(String url) {
        JSONArray jsonArray = new JSONArray();
        return doPost(url, jsonArray);
    }
}
